//
//  CMDBProductionEditViewController.swift
//  CMDB
//
//  Created by 曹桂祥 on 2017/5/18.
//  Copyright © 2017年 CMDB. All rights reserved.
//

import UIKit

private let EditCellID = "EditCell"

private let reuseHeader: String = "ShowTitleView"

private let KPopWidth = CMDB_Screen_Width - 2 * KleftMargin

class CMDBProductionEditViewController: CMDBBaseViewController {
    
    var listArr : [String] = [String]()
    
    var popTitleView : UIView!
    
    var bottomView : UIView!
    
    var allTags : [CMDBShowTags] = [CMDBShowTags]()
    
    var returnTags : [CMDBTagModel] = [CMDBTagModel]()
    
    var sectionTitles : [String] = [String]()
    
    var tagsCollectionView : CMDBEditProductionCollectionView!
    
    lazy var collectionView : UICollectionView = {[weak self] in
        
        //1.创建layout
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = CGSize(width: 100, height: 30)
        
        layout.minimumLineSpacing = 10
        
        layout.minimumInteritemSpacing = 10
        
        layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        
        layout.scrollDirection = .Vertical
        
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        
        collectionView.showsVerticalScrollIndicator = false
        
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.bounces = false
        
        collectionView.delegate = self
        
        collectionView.dataSource = self
        
        collectionView.clipsToBounds = false
        
        collectionView.pagingEnabled = true
        
        collectionView.registerClass(CMDBTagCollectionCell.self, forCellWithReuseIdentifier: EditCellID)
        
        collectionView.registerClass(CMDBEditTagHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: reuseHeader)
        
        collectionView.backgroundColor = UIColor.whiteColor()
        
        return collectionView
        
        }()
    
    var longPress : UILongPressGestureRecognizer!
    
    override func setup() {
        super.setup()
        
        requestData()
        
        buildPopTitleView()
        
        buildCollectionView()
        
        buildBottomView()
        
        buildPickerView()
    }

}

extension CMDBProductionEditViewController{
    
    private func requestData(){
        
        listArr = ["2","3","4"]
        
        let tagName1 = ["导演","演员","主演","录音","摄影","指导"]
        
//        let tagName2 = ["隐藏标签","录音","摄影","指导"]
        
        sectionTitles = ["显示"]
        
        var tags1    = [CMDBTagModel]()
        
        var tags2    = [CMDBTagModel]()
        
        allTags  = [CMDBShowTags]()
        
        for (index,nameString) in tagName1.enumerate() {
            
            tags1.append(CMDBTagModel(tagName: nameString, isSelected: index < 2 ? true : false))
            
        }
        
//        _ = tagName1.map({
//            
//            tags1.append(CMDBTagModel(tagName: $0))
//            
//        })
        
       
        
//        _ = tagName2.map({
//            tags2.append(CMDBTagModel(tagName: $0))
//        })
        
        
        allTags.append(CMDBShowTags(titleName: sectionTitles[0], tags: tags1))
        
//        allTags.append(CMDBShowTags(titleName: sectionTitles[1], tags: tags2))
    }
    
}


extension CMDBProductionEditViewController{
    
    private func buildPopTitleView(){
        
        popTitleView = UIView(frame: CGRect(x: 0, y: 0, width: KPopWidth, height: 44))
        
        popTitleView.backgroundColor = UIColor.whiteColor()
        
        let titleLabel = UILabel(frame: popTitleView.frame)
        
        titleLabel.textAlignment = .Center
        
        titleLabel.textColor = word87Color
        
        titleLabel.text = "属性标签"
        
        popTitleView.addSubview(titleLabel)
        
        view.addSubview(popTitleView)
        
    }
    
    private func buildCollectionView(){
        
        collectionView.frame = CGRect(x: 0, y: 44, width: KPopWidth, height: KPopWidth * 1.5)
        
        longPress = UILongPressGestureRecognizer(target: self, action: #selector(lonePressMoving(_:)))
        
        collectionView.addGestureRecognizer(longPress)
        
        view.addSubview(collectionView)
    }
    
    private func buildCollectionView1(){
        
//        let layout =  //1.创建layout
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = CGSize(width: 125, height: 30)
        
        layout.minimumLineSpacing = 10
        
        layout.minimumInteritemSpacing = 10
        
        layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        
        layout.scrollDirection = .Vertical

        tagsCollectionView = CMDBEditProductionCollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        
        view.addSubview(tagsCollectionView)
        
        tagsCollectionView.allTags = allTags
        
        tagsCollectionView.frame = view.bounds
        
        tagsCollectionView.sectionTitles = sectionTitles
        
    }
    
    private func buildBottomView(){
    
        bottomView = UIView.getInstance()
        
        view.addSubview(bottomView)
        
        bottomView.snp_makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(150)
            make.bottom.equalTo(0)
        }
        
        let buttonView = UIView.getInstance()
        
        bottomView.addSubview(buttonView)
        
        let showCountView = UIView(frame: CGRect(x: 0, y: 35, width: KPopWidth, height: 100 - 44))
        
        bottomView.addSubview(showCountView)
        
        let showCountTextLabel   = UILabel.getInstance()
        
        showCountTextLabel.text  = "请选择您要显示的属性标签个数 :"
        
        showCountTextLabel.textColor = word87Color
        
        showCountTextLabel.font  = CMDB_12_FONT
        
        showCountTextLabel.sizeToFit()
        
        showCountTextLabel.frame = CGRect(x: 10, y: 0, width: showCountTextLabel.width, height: showCountTextLabel.height)
        
        showCountView.addSubview(showCountTextLabel)
        
        
        buttonView.snp_makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(44)
            make.bottom.equalTo(0)
        }
        
        buttonView.addSubview(UIView.CreateLine(CGRect(x: 0, y: 0, width: KPopWidth, height: 0.5), lineColor: word38Color))
        
        buttonView.addSubview(UIView.CreateLine(CGRect(x: KPopWidth, y: 044, width: 0.5, height: 0.5), lineColor: word38Color))
        
        let cancelBtn = UIButton.getInstance()
        
        cancelBtn.frame = CGRect(x: 0, y: 0, width: KPopWidth * 0.5, height: 44)
        
        cancelBtn.setTitle("取消", forState: .Normal)
        
        cancelBtn.titleLabel?.font = CMDB_14_FONT
        
        cancelBtn.setTitleColor(word87Color, forState: .Normal)
        
        cancelBtn.addTarget(self, action: #selector(cancel), forControlEvents: .TouchUpInside)
        
        buttonView.addSubview(cancelBtn)
        
        let submitBtn = UIButton(frame: CGRect(x: KPopWidth * 0.5, y: 0, width: KPopWidth * 0.5, height: 44))
        
        submitBtn.titleLabel?.font = CMDB_14_FONT
        
        submitBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        
        submitBtn.backgroundColor  = UIColor.redColor()
        
        submitBtn.setTitle("提交", forState: .Normal)
        
        submitBtn.addTarget(self, action: #selector(submit), forControlEvents: .TouchUpInside)
        
        buttonView.addSubview(submitBtn)
        
        
    }
    
    func buildPickerView(){
        
        let pickerView = UIPickerView(frame: CGRect(x: 0.55 * KPopWidth, y: 0, width: 0.4 * KPopWidth, height: 80))
        
        bottomView.addSubview(pickerView)
        
        pickerView.showsSelectionIndicator = true
        
        pickerView.dataSource = self
        
        pickerView.delegate = self
        
    }

}

extension CMDBProductionEditViewController : UICollectionViewDataSource{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return allTags.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return allTags[section].tags.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EditCellID, forIndexPath: indexPath) as! CMDBTagCollectionCell
        
        cell.tagModel = allTags[indexPath.section].tags[indexPath.item]
        
        return cell
        
    }
    
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        
        if kind == UICollectionElementKindSectionHeader {
            
            let header = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: reuseHeader, forIndexPath: indexPath) as! CMDBEditTagHeaderView
            
            header.textLabel.text = sectionTitles[indexPath.section]
            
            return header
        } else {
            
            return UICollectionReusableView()
        }
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        return CGSizeMake(KPopWidth, 20)
    }
}

extension CMDBProductionEditViewController : UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
        
        let sourceTag = allTags[sourceIndexPath.section].tags[sourceIndexPath.item]
        
        printLog(sourceIndexPath.section)
        
        printLog(destinationIndexPath)
        
        allTags[sourceIndexPath.section].tags.removeAtIndex(sourceIndexPath.item)
        
        allTags[destinationIndexPath.section].tags.insert(sourceTag, atIndex: destinationIndexPath.item)
        
        collectionView.reloadData()
    }
    
}

//MARK:- action methods
extension CMDBProductionEditViewController{
    
    @objc func cancel(){
        
        dismissViewControllerAnimated(true) { 
            
        }
    }
    
    @objc func submit(){
        
        printLog(submit)
    }
    
}

extension CMDBProductionEditViewController : UIPickerViewDelegate{
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return listArr.count
    }
    
}

extension CMDBProductionEditViewController : UIPickerViewDataSource{
    
    func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        
        return 50
        
    }
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        returnTags.removeAll()
        
        for (_,tagModel) in allTags[0].tags.enumerate() {
            
            tagModel.isSelected = false
            
        }

        
        for (index,tagModel) in allTags[0].tags.enumerate() {
            if index < row + 2 {
                
                tagModel.isSelected = true
                
                returnTags.append(tagModel)
            }
        }
        
        collectionView.reloadData()
        
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return listArr[row]
    }


}

//MARK:- Gester actions
extension CMDBProductionEditViewController{
    
    @objc func lonePressMoving(gester : UILongPressGestureRecognizer){

        switch gester.state {
        case .Began:
            
            let selectedIndexPath = collectionView.indexPathForItemAtPoint(gester.locationInView(collectionView))
            
            printLog(selectedIndexPath?.section)
            
            collectionView.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath!)
            
            break
        case .Changed:
            collectionView.updateInteractiveMovementTargetPosition(gester.locationInView(collectionView))
            
            break
            
        case .Ended:
            collectionView.endInteractiveMovement()
            
            break
        default:
            collectionView.cancelInteractiveMovement()
            
            printLog("default")
        }
        
    }
    
}



